// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package user

import (
	"audio-server/internal/model"
	"audio-server/internal/result"
	"audio-server/internal/sqlutil"
	"audio-server/internal/svc"
	"audio-server/internal/types"
	"context"
	"fmt"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginUserReq) (resp *types.BaseMsgResp, err error) {
	userModel := model.NewUsersModel(l.svcCtx.Conn)
	u, err := userModel.FindByUsername(l.ctx, req.Username)
	if err != nil {
		return result.Fail("用户名或密码错误"), nil // 返回统一错误格式
	}
	password := req.Password
	hash := sqlutil.CheckPasswordHash(password, u.Password)
	if !hash {
		return result.Fail("用户名或密码错误"), nil
	}

	secret := l.svcCtx.Config.Auth.AccessSecret
	expire := l.svcCtx.Config.Auth.Expire
	token, err := result.GetJwtToken(secret, time.Now().Unix(), expire, u.Id)
	err = l.svcCtx.Redis.Set("accessToken:"+fmt.Sprint(u.Id), token)
	if err != nil {
		return result.Fail("redis保存失败"), nil
	}
	if err != nil {
		l.Logger.Error(err)
		return result.Fail("生成token失败"), nil
	}
	return result.Success(types.LoginResp{
		Token: token,
	}), nil
}
